package com.yohann.course_service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yohann.course_service.client.AliClient;
import com.yohann.course_service.entity.Video;
import com.yohann.course_service.mapper.VideoMapper;
import com.yohann.course_service.service.VideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 小节 服务实现类
 * </p>
 *
 * @author Yohann
 * @since 2020-10-18
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Autowired
    private AliClient aliClient;

    /**
     * 删除章节对应的所有小节信息
     *
     * @param chapterId
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void removeAllVideo(int chapterId) {
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Video::getChapterId, chapterId);
        List<Video> videoList = baseMapper.selectList(queryWrapper);

        //删除数据库中小节数据
        baseMapper.delete(queryWrapper);

        List<String> videoIds = videoList.stream().filter(e -> e.getVideoId() != null && !"null".equals(e.getVideoId()))
                .map(Video::getVideoId).collect(Collectors.toList());

        if (!videoIds.isEmpty()) {
            //删除阿里云中视频数据
            aliClient.deleteBatch(videoIds);
        }
    }

    /**
     * 删除小节
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void deleteById(int id) {
        Video video = baseMapper.selectById(id);

        //小节信息
        baseMapper.deleteById(id);

        if (video.getVideoId() != null && !"".equals(video.getVideoId())) {
            //删除阿里云中的视频
            aliClient.deleteVideo(video.getVideoId());
        }
    }
}